import { getUserInfo, login } from '@/api/user'

const state = {
  token: null,
  userInfo: {}
}
const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  REMOVE_TOKEN(state) {
    state.token = null
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  login({ commit }, userInfo) {
    const { mobile, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ mobile: mobile, password: password }).then(response => {
        commit('SET_TOKEN', response)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  logout({ commit }) {
    commit('REMOVE_TOKEN')
    commit('removeUserInfo')
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
